package main

import (
	"fmt"
	"gin/common"
	"gin/routers"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"os"
)

func main() {
	//读取配置文件
	InitConfig()
	//初始化数据库
	db := common.InitDB()
	defer func(db *gorm.DB) {
		err := db.Close()
		if err != nil {
			fmt.Printf("关闭数据库错误, err:%v\n\n", err)
		}
	}(db)
	//初始化redis
	err := common.InitRedisClient()
	if err != nil {
		return
	}
	//加载路由
	r := routers.SetupRouter()
	//启动时开启的端口
	port := viper.GetString("server.port")
	if port != "" {
		if err := r.Run(":" + port); err != nil {
			fmt.Printf("启动服务失败, err:%v\n\n", err)
		}
		return
	}
	if err := r.Run(); err != nil {
		fmt.Printf("启动服务失败, err:%v\n\n", err)
	}
}

func InitConfig() {
	workDir, _ := os.Getwd()
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	viper.AddConfigPath(workDir + "/config")
	err := viper.ReadInConfig()
	if err != nil {

	}
}
